package com.wjc.myktapplication.page.wxaccount

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.wjc.myktapplication.cusview.paging.ui.PostsLoadStateAdapter
import com.wjc.basemodule.base.BaseFragment
import com.wjc.basemodule.base.DataBindingConfig
import com.wjc.basemodule.utils.LogTools
import com.wjc.myktapplication.R
import com.wjc.myktapplication.databinding.FragmentArtWxBinding
import kotlinx.android.synthetic.main.fragment_art_wx.*
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch


private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 公众号 -- tab item
 */
class WxArtFragment : BaseFragment<FragmentArtWxBinding>() {
    private var wxArtAdapter: WxArtAdapter? = null
    private var param1: String? = null
    private var courseId: Int = -1
    private lateinit var accountVm: AccountViewModel

    override val dataBindingConfig: DataBindingConfig
        get() = DataBindingConfig(R.layout.fragment_art_wx)

    companion object {
        fun newInstance(param1: String, cusId: Int?) =
            WxArtFragment().apply {
                arguments = Bundle().apply {
                    putString(param1, ARG_PARAM1)
                    putInt(ARG_PARAM2, cusId ?: -1)
                }
            }
    }

    override fun initViewModel() {
        accountVm = getFragmentViewModel(AccountViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            courseId = it.getInt(ARG_PARAM2)
        }
        LogTools.d("TAG", ": courseId=$courseId")
    }

    override fun onResume() {
        super.onResume()
        initRecyclerView()
        initSwipeToRefresh()
    }

    private fun initSwipeToRefresh() {
        lifecycleScope.launchWhenCreated {
            wxArtAdapter?.loadStateFlow?.collect { loadStates ->
                binding.swipeRefresh.isRefreshing = loadStates.mediator?.refresh is LoadState.Loading
            }
        }
        binding.swipeRefresh.setOnRefreshListener {
            wxArtAdapter?.refresh()
            LogTools.i("TAG", ":wxArtAdapter refresh")
        }
    }

    private fun initRecyclerView() {
        wxArtAdapter = WxArtAdapter()
        rv_wx_art.adapter = wxArtAdapter
        lifecycleScope.launch {
            accountVm.fetWxArtLists(courseId).collectLatest {
                wxArtAdapter?.submitData(it)
            }
        }

        binding.rvWxArt.adapter = wxArtAdapter?.withLoadStateHeaderAndFooter(
            header = PostsLoadStateAdapter(),
            footer = PostsLoadStateAdapter()
        )

        // 监听数据的状态，显示不同的状态
        wxArtAdapter?.addLoadStateListener {
            LogTools.d("TAG", ": it=$it")
            when (it.refresh) {   // 监听初始化数据加载时候的状态(成功,失败)
                is LoadState.NotLoading -> { // 当前未加载
                    defaultPage?.hideLoading()
                }
                is LoadState.Loading -> {
                    defaultPage?.startLoading()
                }
                is LoadState.Error -> {
                    LogTools.d("TAG", "---: e=" + (it.refresh as LoadState.Error).error)
                    defaultPage?.hideLoading()
                    defaultPage?.showNetworkErrorContent(null)
                }
            }
            when (it.prepend) {  // 监听往头部添加数据的时候的状态(成功,失败)
                is LoadState.NotLoading -> { // 当前未加载

                }
                is LoadState.Loading -> {

                }
                is LoadState.Error -> {
                    LogTools.d("TAG", ": e=" + (it.prepend as LoadState.Error).error)
                }
            }

            when (it.append) {   // 监听上拉加载更多的时候的数据状态
                is LoadState.NotLoading -> { // 当前未加载

                }
                is LoadState.Loading -> {

                }
                is LoadState.Error -> {
                    LogTools.d("TAG", ": e=" + (it.append as LoadState.Error).error)
                }
            }
        }
    }


}